package com.jc.common.redis;

/**
 * 由redis实现的简单分布式建议锁
 * @author wuxin
 *
 */
public class DistributedLock {
	private RedisTemplate redisTemplate;

	public void setRedisTemplate(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	/**
	 * 获取锁,返回null未获得锁
	 * @param lock
	 * @return 
	 */
	public String acquireLock(String lock) {
		if (lock == null || lock.length() == 0) {
			return null;
		}

		long inc = redisTemplate.inc(lock);
		if (inc != 1){
			//redisTemplate.decr(lock); //不需要decr，因为采用delkey释放
			return null;
		}else{
			return lock;
		}
		
	}

	/**
	 * 释放锁
	 * @param lock
	 */
	public void releaseLock(String lock){
		if (lock == null || lock.length() == 0) {
			return ;
		}
		redisTemplate.delKey(lock);
		// redisTemplate.decr(lock);
	}
	
}
